package org.formal.system.service.impl;

import java.util.List;
import java.util.Map;

import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.formal.system.service.WorkflowService;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 工作流
 * @author jiangyan
 *
 */
public class WorkflowServiceImpl implements WorkflowService{
	
	@Autowired
	private RuntimeService runtimeService;
	
	@Autowired
	private TaskService taskService;
	
	@Autowired
	private HistoryService historyService;
	
	/**
	 * 开启流程
	 */
	@Override
	public ProcessInstance startProcessBykey(String key) {
		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(key);
		return processInstance;
	}
	
	/**
	 * 开启流程
	 */
	@Override
	public ProcessInstance startProcessBykey(String key,Map<String,Object> variables) {
		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(key,variables);
		return processInstance;
	}
	
	/**
	 * 将任务授权给用户
	 * 
	 */
	public void assignUser(String taskId,String userId) {
		taskService.claim(taskId, userId);
	}
	
	/**
	 * 根据用户id查询代办任务
	 */
	@Override
	public List<Task> getTasksByUserId(String userId) {
		List<Task> taskList = taskService.createTaskQuery().taskCandidateUser(userId).list();
		return taskList;
	}
	
	/**
	 * 根据分组名称查询代办任务
	 */
	@Override
	public List<Task> getTasksByGroupId(String groupId) {
		List<Task> taskList = taskService.createTaskQuery().taskCandidateGroup(groupId).list();
		return taskList;
	}
	
	/**
	 * 查询历史任务数据id
	 * 
	 */
	public List<HistoricTaskInstance> getHistorysByUserId(String userId){
		List<HistoricTaskInstance> historyList = historyService.createHistoricTaskInstanceQuery().taskId(userId).list();
		return historyList;
		
	}
	
	/**
	 * 根据条件完成待办任务
	 */
 	@Override
	public Boolean completeTask(String taskId, Map<String,Object> variables) {
 		taskService.complete(taskId, variables);
		return null;
	}
 	
 	/**
	 * 根据条件完成批量待办任务
	 */
	@Override
	public Boolean completeTasks(List<String> taskIds,  Map<String,Object> variables) {
		taskIds.forEach(taskId->{
			taskService.complete(taskId, variables);
		});
		return null;
	}

	
}
